<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\TokenEnum;
use app\service\token\MediaService;
use app\service\token\TokenInterface;
use app\service\token\TokenService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class RefreshTokenListWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('refresh_token_list_work');
        $this->setDescription('刷新token桶队列');
        $this->addArgument('type', Argument::REQUIRED, '类型 1生产  2消费');
        $this->addArgument('media_id', Argument::REQUIRED, '媒体 1巨量  2快手  5广点通 3金牛');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $type = $input->getArgument('type');
        $mediaId = intval($input->getArgument('media_id'));
        $output->writeln('=======刷新token桶开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            $service = TokenService::getInstance($mediaId);
            if (! $service instanceof TokenInterface) {
                $output->writeln('=======刷新token桶失败: 服务错误' . date('Y-m-d H:i:s', time()) . '=======');
            }
            if ($type == 1) {
                $this->makeList($service);
            } else {
                $this->makeToken($service);
            }
        } catch (\Exception $e) {
            dump($e);
            $output->writeln('=======刷新token桶失败' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '=======');
        }
        $output->writeln('=======刷新token桶结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 生成id队列.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function makeList(MediaService $service)
    {
        $list = $service->getMediaAppTokenList(TokenEnum::TOKEN_STATUS_OK);
        $redis = Cache::store('redis')->handler();
        $redisKey = $service->getListKey();
        $st = time() + 5 * 60;
        while (time() < $st) {
            if ($redis->lLen($redisKey) < 2000) {
                foreach ($list as $v) {
                    $value = $service->getListValue($v);
                    $redis->rPush($redisKey, $value);
                }
            }
            usleep(100000);
        }
    }

    /**
     * 生成token队列.
     * @param mixed $service
     */
    private function makeToken(MediaService $service)
    {
        $redis = Cache::store('redis')->handler();
        $st = time() + (5 * 60);
        while (time() < $st) {
            $tokenData = $redis->lPop($service->getListKey());
            if ($tokenData) {
                $tokenData = json_decode($tokenData, true);
                $tokenKey = $service->getTokenKey($tokenData);
                $token = $service->getToken($tokenData);
                $tokenNum = $tokenData['num'] ?? TokenEnum::TOKEN_REDIS_NUM;
                if ($token && $redis->lLen($tokenKey) < $tokenNum) {
                    for ($j = 0; $j < $tokenNum; ++$j) {
                        $redis->rPush($tokenKey, $token);
                    }
                }
            } else {
                usleep(150000);
            }
        }
    }
}
